<template>
  <div>
    <el-card>
      <el-button type="primary" icon="Plus" @click="openDialog('添加品牌')" v-role-button="`btn.Trademark.add`">添加品牌</el-button>
      <el-table v-loading="loading" class="table" border :data="dataList">
        <el-table-column label="id" width="80" align="center" prop="id"></el-table-column>
        <el-table-column label="名称" align="center" prop="tmName"></el-table-column>
        <el-table-column label="LOGO" align="center" width="120">
          <template v-slot="{row}">
            <div>
              <img :src="row.logoUrl" alt="无图片" style="width: 80px;height: 80px">
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{row}">
            <el-button type="primary" icon="Edit" @click="openDialog('修改品牌', row)" v-role-button="`btn.Trademark.update`">修改</el-button>
            <el-popconfirm title="确认要删除此数据吗？" icon="Delete" width="200" @confirm="deleteTrademark(row.id)" v-role-button="`btn.Trademark.remove`">
              <template v-slot:reference>
                <el-button type="danger" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          background
          :page-sizes="[20, 50, 100, 200, 300, 400]"
          layout="prev, pager, next, jumper, ->, total, sizes"
          :total="total"
          @currentChange="currentChange"
          @sizeChange="sizeChange"
      ></el-pagination>
    </el-card>
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" @closed="closeDialog">
      <el-form style="width: 80%" label-width="100" :model="trademarkForm" :rules="trademarkFormRules" ref="formRef">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input placeholder="请输入品牌名称" v-model="trademarkForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
          >
            <img v-if="trademarkForm.logoUrl" :src="trademarkForm.logoUrl" class="avatar" :alt="trademarkForm.logoUrl"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref, reactive, useTemplateRef} from 'vue';
import {reqTrademarkList, reqTrademarkAddOrUpdate, reqTrademarkDelete} from "@/api/product/trademark";
import type {recordsInter, trademarkInter} from "@/api/product/trademark/type.ts";
import {ElMessage, type FormInstance, type UploadProps} from "element-plus";
// 当前页码
let currentPage = ref<number>(1);
// 每页条数
let pageSize = ref<number>(20);
let total = ref<number>(0)
let dataList = ref<recordsInter[]>([])
let loading = ref<boolean>(false)

onMounted(() => {
  getDataList()
})

// 获取数据函数
const getDataList = async () => {
  loading.value = true
  let res: trademarkInter = await reqTrademarkList(currentPage.value, pageSize.value)
  if (res.code === 200) {
    total.value = res.data.total
    dataList.value = res.data.records
  } else {
    ElMessage.error(res.message)
  }
  loading.value = false
}
const currentChange = (newPage: number) => {
  currentPage.value = newPage
  getDataList()
}
const sizeChange = (newSize: number) => {
  pageSize.value = newSize
  getDataList()
}

// 弹出框
let dialogFormVisible = ref<boolean>(false)
let dialogTitle = ref<string>('添加品牌')
let trademarkForm = reactive<recordsInter>({
  tmName: '',
  logoUrl: ''
})

// 校验图片
const validateLogoUrl = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请上传品牌LOGO'))
  } else {
    callback()
  }
}
// 校验规则
let trademarkFormRules = {
  tmName: [
    {required: true, message: '请输入品牌名称', trigger: 'blur'}
  ],
  logoUrl: [
    {required: true, message: '请上传品牌LOGO', validator: validateLogoUrl}
  ]
}
let formRef = useTemplateRef<FormInstance>('formRef')

const openDialog = (title: string, row?: recordsInter) => {
  dialogTitle.value = title
  dialogFormVisible.value = true
  if (row) {
    trademarkForm.id = row.id
    trademarkForm.tmName = row.tmName
    trademarkForm.logoUrl = row.logoUrl
  }
}

// 取消
const cancel = () => {
  dialogFormVisible.value = false
}
// 确定
const confirm = async () => {
  await formRef.value?.validate(async valid => {
    if (!valid) return
    let res = await reqTrademarkAddOrUpdate(trademarkForm)
    if (res.code === 200) {
      ElMessage.success('操作成功')
      dialogFormVisible.value = false
      await getDataList()
    } else {
      ElMessage.error(res.message)
    }
  })
}
const closeDialog = () => {
  formRef.value?.resetFields()
  trademarkForm.id = 0
  trademarkForm.tmName = ''
  trademarkForm.logoUrl = ''
}
// 删除
const deleteTrademark = async (id: number) => {
  let res = await reqTrademarkDelete(id)
  if (res.code === 200) {
    ElMessage.success('操作成功')
    dataList.value.length > 1 ? currentPage.value : currentPage.value - 1
    await getDataList()
  } else {
    ElMessage.error(res.message)
  }
}

// 图片上传
const handleUploadSuccess: UploadProps['onSuccess'] = (res) => {
  trademarkForm.logoUrl = res.data
  formRef.value?.clearValidate('logoUrl')
}
const beforeUpload: UploadProps['beforeUpload'] = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
    return false
  }
}
</script>

<style lang="scss">
.table {
  margin: 20px 0;
}

.avatar-uploader {
  .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }

    .avatar {
      width: 180px;
      height: 180px;
    }
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
